package com.dongdongshop.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //创建shiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        //shiro的过滤器里面,优先放过某些,然后我们才可以拦截所有等等,所以我们需要一个LinkedHashMap :有序的,唯一的
        Map<String, String> map = new LinkedHashMap<String, String>();
        //key表示路径,value叫过滤器,表示我们当前路径如何过滤
        map.put("/img/**","anon");
        map.put("/css/**","anon");
        map.put("/plugins/**","anon");
        //放过登录
        map.put("/login/login","anon");
        map.put("/seller/show","anon");
        //退出登录
        map.put("/logout","logout");
        //拦截所有
        map.put("/**","authc");
        shiroFilter.setFilterChainDefinitionMap(map);
        //跳转登陆页面
        shiroFilter.setLoginUrl("/login/show");
        //需要将安全管理器放入过滤工厂类中
        shiroFilter.setSecurityManager(defaultWebSecurityManager);
        return shiroFilter;
    }


    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm
        securityManager.setRealm(loginRealm);
        return securityManager;
    }

    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher) {
        LoginRealm realm = new LoginRealm();
        realm.setCredentialsMatcher(hashedCredentialsMatcher);
        return realm;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //配置加密算法 MD5
        matcher.setHashAlgorithmName("MD5");
        //迭代次数
        matcher.setHashIterations(3);
        //设置加密密码
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;
    }
}
